package com.lk.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lk.common.ErrorCode;
import com.lk.common.Result;
import com.lk.exception.BusinessException;
import com.lk.model.domain.User;
import com.lk.model.request.UserLoginRequest;
import com.lk.model.request.UserQueryRequest;
import com.lk.model.request.UserRegisterRequest;
import com.lk.model.request.UserUpdatePassword;
import com.lk.service.UserService;
import com.lk.utils.AliOssUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.lk.constant.UserConstant.ADMIN_ROLE;
import static com.lk.constant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
//@CrossOrigin(origins = {"http://localhost:3000","http://keyl1001.top","http://www.keyl1001.top"})
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private StringRedisTemplate strRedisTemplate;

    @Resource
    private AliOssUtil aliOssUtil;

    /**
     * 注册(账户、密码)
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public Result<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userName = userRegisterRequest.getUserName();
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        if (StringUtils.isAnyBlank(userName,userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = userService.userRegister(userName,userAccount, userPassword, checkPassword);

        return Result.success(id);
    }



    /**
     * 查询用户
     *
     * @param username
     * @param request
     * @return
     */
    @GetMapping("/search")
    public Result<List<User>> searchUsers(String username, HttpServletRequest request) {
        //判断是否是管理员
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);

        //遍历查询结果，把每一个user对象的密码设置为null
  /*    return userList.stream().map(user -> {
            user.setUserPassword(null);
            return user;
        }).collect(Collectors.toList());          */

        List<User> list = userList.stream().map(user -> {
            return userService.getSafetyUser(user);
        }).collect(Collectors.toList());

        return Result.success(list);
    }



    /**
     * 删除用户(逻辑删除)
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public Result<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        //仅管理员可查询
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return Result.success(b);
    }


    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<Boolean> Logout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Boolean b = userService.userLogout(request);

        return Result.success(b);
    }


    /**
     * 判断是否是管理员
     *
     * @param request
     * @return
     */
    private boolean isAdmin(HttpServletRequest request) {
        Long id = Long.valueOf(request.getHeader("userId"));
        String key = USER_LOGIN_STATE + ":" + id;
        String userStr = strRedisTemplate.opsForValue().get(key);
        User user = JSONArray.parseObject(userStr, User.class);
        return user != null && user.getUserRole() == ADMIN_ROLE;
    }


    /**
     * 按标签搜索用户
     *
     * @param tagNameList 标记名称列表
     * @param currentPage 当前页面
     * @param request     要求
     * @return {@link Result}<{@link Page}<{@link User}>>
     */
    @GetMapping("/search/tags")
    @ApiOperation(value = "通过标签搜索用户")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "tagNameList", value = "标签列表")})
    public Result<Page<User>> searchUsersByTags(@RequestParam(required = false) List<String> tagNameList,
                                                      long currentPage, HttpServletRequest request) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Page<User> userList = userService.searchUsersByTags(tagNameList, currentPage);
        return Result.success(userList);
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/update")
    public Result<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        // 校验参数是否为空
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        int result = userService.updateUser(user, loginUser);
        return Result.success(result);
    }


    /**
     * 头像上传OSS
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploadAvatar")
    public Result<Integer> upload(@RequestBody MultipartFile file,User user,HttpServletRequest request){

        if (user == null|| file == null ){
            return Result.error(ErrorCode.PARAMS_ERROR,"请正确选择头像");
        }
        User orgUser = userService.getById(user.getId());
        String avatarUrl = orgUser.getAvatarUrl();

            //如果之前有头像，则删除
            if(avatarUrl != null) {
            int i = avatarUrl.lastIndexOf('/');
            String substring = avatarUrl.substring(i + 1);
            //删除之前的头像
            aliOssUtil.delete(substring);
            }

        //上传头像
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名
            String objectName = UUID.randomUUID().toString();
            objectName=objectName+extension;
            //文件请求路径
            String Path = aliOssUtil.upload(file.getBytes(), objectName);

            System.out.println("Avatar路径："+Path);

            if (StringUtils.isNotBlank(Path)){
                user.setAvatarUrl(Path);
                User loginUser = userService.getLoginUser(request);
                int result = userService.updateUser(user, loginUser);
                return Result.success(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error(ErrorCode.SYSTEM_ERROR,"头像更新失败");
    }


    /**
     * 登录(账户、密码)
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        if (user == null){
            return Result.error(ErrorCode.USER_NOT_EXIT,"登录失败");
        }
        return Result.success(user);
    }

    /**
     * 获取当前登录用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    @ApiOperation(value = "获取当前登录用户信息")
    public Result<User> getCurrentUser(HttpServletRequest request) {
        Long id = Long.valueOf(request.getHeader("userId"));

        String key= USER_LOGIN_STATE+ ":" + id;
//        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        String userStr = strRedisTemplate.opsForValue().get(key);
        User loginUser = JSONArray.parseObject(userStr, User.class);
//        User currentUser = (User) userObj;
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
//        Long id = loginUser.getId();
//        User user = userService.getById(id);
        User user = userService.getById(loginUser.getId());
        User safetyUser = userService.getSafetyUser(user);

        return Result.success(safetyUser);
    }

    /**
     * 根据搜索条件查找
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search")
    public Result<List<User>> userQuery(@RequestBody UserQueryRequest userQueryRequest, HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        List<User> users = userService.userQuery(userQueryRequest, request);
        return Result.success(users);
    }

    /**
     * 获取标签和自己最匹配的用户
     *
     * @param num
     * @param request
     * @return
     */
    @GetMapping("/match")
    public Result<List<User>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        return Result.success(userService.matchUsers(num, user));
    }

    /**
     * 分页查找(包括自己)
     *
     * @param pageSize
     * @param pageNum
     * @param request
     * @return
     */
    @GetMapping("/recommend")
    public Result<Page<User>> recommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String redisKey = String.format("CodePartner:user:recommend:%s", loginUser.getId());
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 如果有缓存，直接读缓存
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);
        if (userPage != null) {
            return Result.success(userPage);
        }
        // 无缓存，查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        // 写缓存
        try {
            valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        log.info("Page total: {}, pages: {}, size: {}, current: {}, records: {}", userPage.getTotal(), userPage.getPages(), userPage.getSize(), userPage.getCurrent(), userPage.getRecords());
        return Result.success(userPage);
    }


    /**
     * 随机推荐用户所有用户(包括自己)
     *
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/random")
    public Result<List<User>> randomUsers(long pageSize, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        //随机推荐用户，不缓存，直接查
        List<User> userPage = userService.random(pageSize);

        System.out.println("随机推荐用户"+userPage);

        return Result.success(userPage);
    }



    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable("id") Integer id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = this.userService.getById(id);
        return Result.success(user);
    }

    @PostMapping("/update/password")
    public Result<Integer> updatePassword(@RequestBody UserUpdatePassword updatePassword, HttpServletRequest request) {
        if (updatePassword == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.getLoginUser(request);
        int updateTag = userService.updatePasswordById(updatePassword, currentUser);
        redisTemplate.delete(userService.redisFormat(currentUser.getId()));
        return Result.success(updateTag);
    }


    @GetMapping("/friends")
    public Result<List<User>> getFriends(HttpServletRequest request) {
        User currentUser = userService.getLoginUser(request);
        List<User> getUser = userService.getFriendsById(currentUser);
        return Result.success(getUser);
    }

    @PostMapping("/deleteFriend/{id}")
    public Result<Boolean> deleteFriend(@PathVariable("id") Long id, HttpServletRequest request) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "好友不存在");
        }
        User currentUser = userService.getLoginUser(request);
        boolean deleteFriend = userService.deleteFriend(currentUser, id);
        return Result.success(deleteFriend);
    }

    @PostMapping("/searchFriend")
    public Result<List<User>> searchFriend(@RequestBody UserQueryRequest userQueryRequest, HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        User currentUser = userService.getLoginUser(request);
        List<User> searchFriend = userService.searchFriend(userQueryRequest, currentUser);
        return Result.success(searchFriend);
    }

    /**
     * 获取用户标签
     *
     * @param request 请求
     * @return {@link Result}<{@link List}<{@link String}>>
     */
    @GetMapping("/tags")
    @ApiOperation(value = "获取当前用户标签")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "request", value = "request请求")})
    public Result<List<String>> getUserTags(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        List<String> userTags = userService.getUserTags(loginUser.getId());
        return Result.success(userTags);
    }

    /**
     * 更新用户标签
     *
     * @param tags    标签
     * @param request 请求
     * @return {@link Result}<{@link String}>
     */
    @PutMapping("/update/tags")
    @ApiOperation(value = "更新用户标签")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "tags", value = "标签"),
                    @ApiImplicitParam(name = "request", value = "request请求")})
    public Result<String> updateUserTags(@RequestBody List<String> tags, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        userService.updateTags(tags, loginUser.getId());
        return Result.success("ok");
    }
    
}
